<template>
  <div>
    <h1>User List</h1>
    <el-table :data="users" style="width: 100%">
      <el-table-column prop="username" label="Username"></el-table-column>
      <el-table-column prop="password" label="Password"></el-table-column>
      <el-table-column prop="status" label="Status"></el-table-column>
      <el-table-column prop="createtime" label="createtime"></el-table-column>
      <el-table-column label="Actions">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="editUser(row)"
            >Edit</el-button
          >
          <el-button type="danger" size="small" @click="deleteUser(row)"
            >Delete</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from "vue";
import { ElTable, ElTableColumn, ElButton } from "element-plus";
import md5 from "md5";

interface User {
  id: number;
  username: string;
  password: string;
  status: number;
  createtime: string;
}

export default defineComponent({
  name: "UserList",
  components: {
    ElTable,
    ElTableColumn,
    ElButton,
  },
  setup() {
    const users = ref<User[]>([]);

    // 在组件初始化时加载表格数据
    fetchUsers();

    async function fetchUsers(): Promise<void> {
      try {
        // 从localStorage中读取token
        var token: string | null = localStorage.getItem("token");

        // 构建请求头，包括token
        const headers = new Headers();
        headers.append("Content-Type", "application/json");
        headers.append("Authorization", `${token}`);

        // 构建请求参数
        const requestOptions: RequestInit = {
          method: "GET",
          headers: headers,
        };

        // 发送POST请求
        const response = await fetch(
          "http://localhost:8080/api/user/auth/getAllUser",
          requestOptions
        );
        const data = await response.json();

        if (response.ok) {
          // 请求成功，将用户数据赋值给users列表
          if (data.success) {
            users.value = data.users;
            token = data.token;
            if (token != null) localStorage.setItem("token", token);
            else throw new Error("token is null");
          } else throw new Error("data.success is false");
        } else {
          // 请求失败，处理错误
          console.error("Error:", response.status);
        }
      } catch (error: any) {
        console.error("Error:", error);
        alert(error.message);
      }
    }

    async function editUser(row: User) {
      // 编辑用户逻辑
      try {
        var user: User = row;
        // 从localStorage中读取token
        const userInput: string | null = window.prompt("请输入一个新的密码:");

        if (userInput !== null) {
          // 用户点击了确认按钮，并且输入了值
          console.log("用户输入的值是:", userInput);
          user.password = md5(userInput);
        } else {
          // 用户点击了取消按钮
            throw Error("用户取消了输入");
        }
        // 从localStorage中读取token
        var token: string | null = localStorage.getItem("token");
        if (token == null) throw new Error("token is null");
        // 构建请求头，包括token
        const headers = new Headers();
        headers.append("Content-Type", "application/json");
        headers.append("Authorization", `${token}`);

        // 构建请求参数
        const requestOptions: RequestInit = {
          method: "POST",
          headers: headers,
          body: JSON.stringify(user),
        };

        console.log("Save user:", requestOptions.body);

        // 发送POST请求
        const response = await fetch(
          "http://localhost:8080/api/user/auth/UpdatePasswordByUsername",
          requestOptions
        );
        const data = await response.json();

        if (response.ok) {
          // 请求成功，将用户数据赋值给users列表
          if (data.success) {
            fetchUsers();
            token = data.token;
            if (token != null) localStorage.setItem("token", token);
            else throw new Error("token is null");
          } else {
            throw new Error("data.success is false");
          }
        } else {
          // 请求失败，处理错误
          console.error("Error:", response.status);
        }
      } catch (error: any) {
        console.error("Error:", error);
        alert(error.message);
      }
    }

    async function deleteUser(user: User) {
      try {
        // 从localStorage中读取token
        var token: string | null = localStorage.getItem("token");
        if (token == null) throw new Error("token is null");

        // 构建请求头，包括token
        const headers = new Headers();
        headers.append("Content-Type", "application/json");
        headers.append("Authorization", `${token}`);

        // 构建请求参数
        const requestOptions: RequestInit = {
          method: "POST",
          headers: headers,
          body: JSON.stringify(user),
        };

        console.log("Delete user:", requestOptions.body);

        // 发送POST请求
        const response = await fetch(
          "http://localhost:8080/api/user/auth/DelUserByUsername",
          requestOptions
        );
        const data = await response.json();

        if (response.ok) {
          // 请求成功，将用户数据赋值给users列表
          if (data.success) {
            fetchUsers();
            token = data.token;
            if (token != null) localStorage.setItem("token", token);
            else throw new Error("token is null");
          } else throw new Error("data.success is false");
        } else {
          // 请求失败，处理错误
          console.error("Error:", response.status);
        }
      } catch (error: any) {
        console.error("Error:", error);
        alert(error.message);
      }
    }

    return {
      users,
      editUser,
      deleteUser,
    };
  },
});
</script>
